package org.metasketch.editor.links;

import org.metasketch.graphics.Point2f;

import javafx.scene.Group;
import javafx.scene.transform.Rotate;

public class LineEnd extends Group {

	public void setNewPosition(int x, int y, int sectionX, int sectionY) {
		double angle = getAngleInDegrees(x, y, sectionX, sectionY);
		doRotation(angle);

		// System.out.println(angle);

		double rightAngle = angle + 270.0;
		Point2f translateVector = getVectorFromAngle(rightAngle);
		translateVector.scale(5.0);

		setTranslateX(x + translateVector.getX());
		setTranslateY(y - translateVector.getY());

		// setTranslateX(x);
		// setTranslateY(y);
	}

	private Point2f getVectorFromAngle(double rightAngle) {

		return new Point2f(Math.cos(Math.toRadians(rightAngle)), Math.sin(Math
				.toRadians(rightAngle)));
	}

	protected Point2f getUnitVector(int x, int y, int sectionX, int sectionY) {
		int dx = x - sectionX;
		int dy = y - sectionY;

		double magV = Math.sqrt(dx * dx + dy * dy);
		double aX = dx / magV;
		double aY = dy / magV;

		return new Point2f(aX, aY);
	}

	protected Point2f getUnitVector(int x, int y, int sectionX, int sectionY,
			double size) {
		int dx = x - sectionX;
		int dy = y - sectionY;

		double magV = Math.sqrt(dx * dx + dy * dy);
		double aX = x - dx / magV * size;
		double aY = y - dy / magV * size;

		return new Point2f(aX, aY);
	}

	protected double getAngleInDegrees(int x, int y, int sectionX, int sectionY) {
		int dx = x - sectionX;
		int dy = y - sectionY;

		return getAngleInDegrees(dx, dy);

	}

	protected double getAngleInDegrees(int vx, int vy) {
		double a = Math.atan2(vx, vy);
		if (a < 0) {
			a += Math.PI * 2.0;
		}
		return Math.toDegrees(a) - 270.0;
	}

	protected void doRotation(double degrees) {
		getTransforms().clear();

		degrees = -degrees + 270.0;

		Rotate rz = new Rotate();
		rz.setAxis(Rotate.Z_AXIS);
		rz.setAngle(degrees);
		getTransforms().add(rz);

	}
}
